package com.thermofisher.dsc.amanda.common;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by wenjie.yang on 1/4/2019.
 */
public class Query extends LinkedHashMap<String, Object> {

  private static final long serialVersionUID = 1L;

  private int page = 1;

  private int length = 15;

  private boolean onepage = false;

  public static String PRECISE_PREFIX = "E_";
  public static String RANGE_PREFIX = "R_";
  public static String OR_PREFIX = "_OR_";
  public static String SELECTED = "selected";

  public static String RANGE_FOUND_YEAR = "R_foundedYear";
  private static int PRECISE_PREFIX_LEN = PRECISE_PREFIX.length();
  public static String ID = "ID";
  public static String ASC = "ASC";
  public static String DESC = "DESC";

  private String orderByClause = ID.concat(" ").concat(ASC);

  public static boolean isPrecise(String key) {
    return key != null && key.startsWith(PRECISE_PREFIX);
  }

  public static boolean isOrderBy(String key) {
    return key != null && key.equals("orderBy");
  }

  public static String removePrefix(String key) {
    return key != null ? key.substring(PRECISE_PREFIX_LEN) : key;
  }


  public String getOrderByClause() {
    return orderByClause;
  }

  public void setOrderByClause(String orderByClause) {
    this.orderByClause = orderByClause;
  }

  public Boolean isOrderByClauseDefault(){
    return getOrderByClause().equals(ID.concat(" ").concat(ASC));
  }

  public Query(Map<String, Object> params) {
    this.putAll(params);
    if (params.get("page") != null) {
      this.setPage(Integer.parseInt(params.get("page").toString()));
    }
    if (params.get("length") != null) {
      this.setLength(Integer.parseInt(params.get("length").toString()));
    }
    /*if (params.get("actionType") != null) {
      this.remove("actionType");
    }*/
    Object onepagestr = params.get("onepage");
    if (onepagestr != null) {
      this.setOnepage(Boolean.parseBoolean(onepagestr.toString()));
    }
    this.remove("page");
    this.remove("length");
    this.remove("onepage");
  }


  public int getPage() {
    return page;
  }

  public void setPage(int page) {
    this.page = page;
  }

  public int getLength() {
    return length;
  }

  public void setLength(int length) {
    this.length = length;
  }

  public boolean isOnepage() {
    return onepage;
  }

  public void setOnepage(boolean onepage) {
    this.onepage = onepage;
  }

  public int getOffset() {
    return this.length * (this.page - 1);
  }
}
